package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.bean.Student;
import com.itheima.mapper.StudentMapper;
import com.itheima.service.StudentService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;

@Service("studentService")
@Transactional
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper mapper;

    /**
     * 分页查询方法
     *
     * @param currentPage 当前页数
     * @param pageSize    每页展示条数
     * @return 返回PageInfo分页结果对象
     */
    @Override
    public PageInfo<Student> selectByPage(int currentPage, int pageSize) {
        //分页
        PageHelper.startPage(currentPage, pageSize);
        //获取mapper对象
        Page<Student> page = mapper.findAll();
        //6 返回结果
        return new PageInfo<>(page);
    }

    /**
     * 添加学生信息
     *
     * @param student 要添加的学生对象
     * @return 返回影响的行数，1表示成功，0表示失败
     */
    @Override
    public int addStudent(Student student) {

        return mapper.addStudent(student);
    }

    /**
     * 修改学生的方法
     *
     * @param student 要修改的学生对象
     * @return 返回影响的行数，1表示成功，0表示失败
     */
    @Override
    public int updateStudent(Student student) {

        return mapper.updateStudent(student);
    }

    /**
     * 删除学生的方法
     *
     * @param number 学生的编号
     * @return 返回影响的行数，1表示成功，0表示失败
     */
    @Override
    public int deleteStudent(String number) {
        /*SqlSession sqlSession = null;
        try {
            //1 加载核心配置文件资源
            InputStream is = Resources.getResourceAsStream("MybatisConfig.xml");
            //2 获取SqlSessionFactory对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //3 获取SqlSession对象
            sqlSession = factory.openSession(true);
            //4 获取mapper的代理对象，执行操作
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            int count = mapper.deleteStudent(number);
            //返回结果
            return count;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //5 释放资源
            if (sqlSession != null) {
                sqlSession.close();
            }
        }*/
        return mapper.deleteStudent(number);
    }
}
